import os
import re
import subprocess
import sys
from time import sleep

BASE_PATH = "/Users/zhangbeibei/Downloads/"


def get_full_path(relative_path):
    relative_path = relative_path.strip('"\"')
    return os.path.join(BASE_PATH, relative_path)


def check_adb_installed():
    """检查系统是否安装了adb工具"""
    try:
        subprocess.run(["adb", "--version"], capture_output=True, check=True)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def install_apk(apk_path):
    """通过adb安装APK到设备"""
    try:
        print(f"正在安装: {apk_path}")
        result = subprocess.run(
            ["adb", "install", "-r", apk_path],
            capture_output=True,
            text=True)
        if "Success" in result.stdout:
            print("✅ 安装成功！")
        else:
            print(f"❌ 安装失败: {result.stderr or result.stdout}")
    except Exception as e:
        print(f"⚠️ 发生异常: {e}")


def extract_package_name(apk_path):
    """从APK路径提取包名（如 com.winmate.native.gg）"""
    apk_name = os.path.basename(apk_path)
    match = re.search(r"_(com\..+?)_\d", apk_name)  # 匹配com.开头到版本号前的部分
    return match.group(1) if match else None


def uninstall_package(pkg_name):
    """静默卸载包（如果存在）"""
    print(f"🔄 尝试卸载: {pkg_name}", end=" → ")
    result = subprocess.run(
        ["adb", "shell", "pm", "uninstall", "--user", "0", pkg_name],
        capture_output=True,
        text=True
    )
    if "Success" in result.stdout:
        print("✅ 卸载成功")
        return True
    elif "not installed" in result.stdout:
        print("⚠️ 未安装")
        return False
    else:
        print(f"❌ 失败: {result.stdout.strip()}")
        return False


def process_apk(apk_path):
    """处理单个APK：卸载旧版 → 安装新版"""
    pkg_name = extract_package_name(apk_path)
    if not pkg_name:
        print(f"⚠️ 无法提取包名: {apk_path}")
        return False

    uninstall_package(pkg_name)
    sleep(1)  # 给设备缓冲时间
    return install_apk(apk_path)





def main():
    # 检查adb是否可用
    if not check_adb_installed():
        print("错误：未检测到adb工具，请确保已安装Android SDK并配置环境变量。")
        sys.exit(1)

    # 获取用户输入的APK路径
    relative_path = input("请输入版本子路径（如/1.6.0/1.6.0/Release_com.winmate.native_1.6.0_202503191149.apk）:")
    apk_path = get_full_path(relative_path)

    # 检查文件是否存在
    if not os.path.exists(apk_path):
        print(f"错误：文件不存在 - {apk_path}")
        sys.exit(1)

    # 执行安装
    process_apk(apk_path)


if __name__ == "__main__":
    main()